<template>
  <div>
    <!-- 新增地址 -->
    <van-address-edit
      :area-list="areaList"
      :addressInfo="addressInfo"
      :show-delete="isdelete"
      show-set-default
      show-search-result
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
      @change-detail="onChangeDetail"
    />
  </div>
</template>

<script>
import router from "@/router";
import request from "@/utils/request";
import { areaList } from "@vant/area-data";
import { showNotify } from "vant";
export default {
  data() {
    return {
      areaList: areaList,
      addressEditInfo: [],
      //   默认地址列表
      addressInfo: {},
      isdelete: false,
    };
  },
  async created() {
    const id = this.$route.query.id;
    if (id) {
      // 控制按钮显示
      this.isdelete = true;
      const result = await request.get(`/good/getresslistid?id=${id}`);
      //   对默认地址进行赋值
      this.addressInfo = {
        name: result.data.resslistdata.name,
        tel: result.data.resslistdata.tel, // 电话号码
        province: result.data.resslistdata.province, // 省名
        city: result.data.resslistdata.city, // 市名
        county: result.data.resslistdata.county, // 区名
        addressDetail: result.data.resslistdata.addressDetail, // 详细地址
        isDefault:
          result.data.resslistdata.isDefault.length == 4 ? true : false, // 是否为默认地址，非必填},
      };
    }
  },
  methods: {
    // 点击保存
    async onSave(info) {
      const id = this.$route.query.id;
      if (id) {
        // 修改并保存地址
        const resslist = {
          ...info,
          id: id,
        };
        const result = await request.post("/good/updateresslist", resslist);
        if (result.data.code === 200) {
          showNotify({ type: "success", message: result.data.message });
          router.replace("/resslist");
        }
        if (result.data.code === 500) {
          showNotify({ type: "warning", message: result.data.message });
        }
      } else {
        // 新增地址
        const result = await request.post("/good/addresslist", info);
        if (result.data.code == 200) {
          showNotify({ type: "success", message: result.data.message });
          router.replace("/resslist");
        }
        if (result.data.code == 500) {
          showNotify({ type: "danger", message: result.data.message });
        }
        if (result.data.code == 400) {
          showNotify({ type: "warning", message: result.data.message });
        }
      }
    },
    // 删除地址
    async onDelete() {
      const id = this.$route.query.id;
      const result = await request.get(`/good/delresslistid?id=${id}`);
      if (result.data.code === 200) {
        router.replace("/resslist");
        showNotify({ type: "success", message: result.data.message });
      }
    },
  },
};
</script>

<style></style>
